<script setup lang="ts">
  import { ref } from 'vue';
  import TableLayout from '@/layout/table-layout.vue';
  import InnerPage from '@/components/inner-page/index.vue';
  import { Message } from '@arco-design/web-vue';
  import { usePageTable } from '@/hooks/arco/usePageTable';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import * as Lodash from 'lodash';
  import { XlsxUtil, getDatetimeFilename } from '@/utils/util';
  import { queryInstDepartments } from '@/api/structure-management/department';
  import { queryInstPositions } from '@/api/structure-management/position';
  import { queryStaffs } from '@/api/structure-management/employee';
  import EditModal from './edit.vue';
  import BaseInfo from './info.vue';

  const loading = ref(false);
  const baseNameMap = {
    itemId: { key: 'staffId', label: '员工ID' },
    itemName: { key: 'staffName', label: '员工姓名' },
    itemGender: { key: 'gender', label: '员工性别' },
    itemGenderName: { key: 'genderName', label: '员工性别' },
    itemPhone: { key: 'phoneNo', label: '联系电话' },
    itemIDCard: { key: 'idCardNo', label: '身份证号' },
    itemStatus: { key: 'jobStatus', label: '就职状态' },
    itemStatusTitle: { key: 'jobStatusTitle', label: '就职状态' },
    itemDepartment: { key: 'department', label: '所属部门' },
    itemPosition: { key: 'position', label: '所在岗位' },
    btnAction: { label: '操作' },
    btnLook: { label: '查看' },
  };

  const dataPage = ref({
    total: 0,
    page: 1,
    pageSize: 10,
  });

  const tableData: any = {};

  const jobStatusOptions = [
    { label: '在职', value: 1 },
    { label: '离职', value: 2 },
  ];

  const departmentSelect = useSelectOption({
    name: baseNameMap.itemDepartment.label,
    apiFun: queryInstDepartments,
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  const positionSelect = useSelectOption({
    name: baseNameMap.itemPosition.label,
    apiFun: queryInstPositions,
    fieldNames: {
      label: 'name',
      value: 'id',
    },
  });

  // 查询表格列配置
  const tableColumns = [
    {
      title: baseNameMap.itemId.label,
      dataIndex: baseNameMap.itemId.key,
      ellipsis: true,
      tooltip: true,
      // width: 200,
    },
    {
      title: baseNameMap.itemName.label,
      dataIndex: baseNameMap.itemName.key,
      ellipsis: true,
      tooltip: true,
      // width: 140,
    },
    {
      title: baseNameMap.itemGenderName.label,
      dataIndex: baseNameMap.itemGenderName.key,
      // width: 120,
    },
    {
      title: baseNameMap.itemPhone.label,
      dataIndex: baseNameMap.itemPhone.key,
      ellipsis: true,
      tooltip: true,
      // width: 160,
    },
    // {
    //   title: baseNameMap.itemIDCard.label,
    //   dataIndex: baseNameMap.itemIDCard.key,
    //   width: 240,
    // },
    {
      title: baseNameMap.itemStatusTitle.label,
      dataIndex: baseNameMap.itemStatusTitle.key,
      // width: 200,
    },
    {
      title: baseNameMap.itemDepartment.label,
      dataIndex: baseNameMap.itemDepartment.key,
      ellipsis: true,
      tooltip: true,
      // width: '300',
    },
    {
      title: baseNameMap.itemPosition.label,
      dataIndex: baseNameMap.itemPosition.key,
      ellipsis: true,
      tooltip: true,
      // width: '300',
    },
    {
      title: baseNameMap.btnAction.label,
      align: 'center' as const,
      dataIndex: 'action',
      slotName: 'action',
      fixed: 'right',
      width: 100,
    },
  ];

  const pageTable = usePageTable({
    batchExport: true,
    searchForm: {
      state: {
        [baseNameMap.itemDepartment.key]: '',
        [baseNameMap.itemPosition.key]: '',
        [baseNameMap.itemName.key]: '',
        [baseNameMap.itemStatus.key]: '',
      },
    },
    table: {
      rowKey: baseNameMap.itemId.key,
      fakePage: true,
      apiFun: async (query) => {
        return new Promise((resolve) => {
          const params = {
            ...dataPage.value,
            departmentId: query[baseNameMap.itemDepartment.key],
            positionId: query[baseNameMap.itemPosition.key],
            staffName: query[baseNameMap.itemName.key],
            jobStatus: query[baseNameMap.itemStatus.key],
          };
          queryStaffs(params).then((res) => {
            dataPage.value.total = res.total;
            const staffs = res.list;
            staffs.map((item: any) => {
              //
              if (item.departments && item.departments.length > 0) {
                item.department = item.departments[0].departmentName;
              }
              if (item.positions && item.positions.length > 0) {
                item.position = item.positions[0].positionName;
              }
              switch (item.gender) {
                case 1: {
                  item.genderName = '男';
                  break;
                }
                case 2: {
                  item.genderName = '女';
                  break;
                }
                default: {
                  item.genderName = '未知';
                }
              }
              //
              return item;
            });
            resolve(staffs);
          });
        });
      },
      onSuccess(data) {
        for (let i = 0; i < data.length; i += 1) {
          const item = data[i];
          const key = baseNameMap.itemId.key as string;
          if (item[key] && !tableData[key]) {
            tableData[item[key]] = Lodash.cloneDeep(item);
          }
        }
        // dataDepartments.value = getDepartmentList(data);
      },
      columns: tableColumns,
      rowSelection: {
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      },
    },
  });

  const editHandler = ref({
    props: {
      data: {} as any,
      visible: false,
      title: '新增员工',
      type: 'add' as any,
    },
    showDrawer: (item: any) => {
      editHandler.value.props.visible = true;
      editHandler.value.props.data = Lodash.cloneDeep(item);
    },
    onSave: (item: any) => {
      pageTable.reload();
    },
  });

  const infoHandler = ref({
    props: {
      [baseNameMap.itemId.key]: '',
    },
    onBack: () => {
      infoHandler.value.props[baseNameMap.itemId.key] = '';
      pageTable.reload();
    },
    onUpdate: () => {
      pageTable.reload();
    },
  });

  const handleLook = (item: any) => {
    infoHandler.value.props[baseNameMap.itemId.key] =
      item[baseNameMap.itemId.key];
    // console.log('to info:', infoHandler.value.props[baseNameMap.itemId.key]);
  };

  /**
   * 表格数据导出
   * @param dataList
   */
  const handleExport = (dataList: any[]) => {
    const filename = getDatetimeFilename('【导出-员工列表】', '.xlsx');
    if (XlsxUtil.writeDownload(filename, dataList)) {
      Message.success('导出成功');
    } else {
      Message.error('导出失败');
    }
  };
</script>

<template>
  <div class="m-employee">
    <div class="m-employee-raw">
      <TableLayout
        v-bind="pageTable.bindProps"
        @create="editHandler.props.visible = true"
        @batch-export="handleExport"
      >
        <template #searchForm="{ state }">
          <!-- 所属部门 -->
          <a-form-item
            :field="baseNameMap.itemDepartment.key"
            :label="baseNameMap.itemDepartment.label"
          >
            <a-select
              v-model="state[baseNameMap.itemDepartment.key]"
              v-bind="departmentSelect.bindProps"
            />
          </a-form-item>
          <!-- 所在岗位 -->
          <a-form-item
            :field="baseNameMap.itemPosition.key"
            :label="baseNameMap.itemPosition.label"
          >
            <a-select
              v-model="state[baseNameMap.itemPosition.key]"
              v-bind="positionSelect.bindProps"
            />
          </a-form-item>
          <!-- 员工姓名 -->
          <a-form-item
            :field="baseNameMap.itemName.key"
            :label="baseNameMap.itemName.label"
          >
            <a-input
              v-model="state[baseNameMap.itemName.key]"
              :placeholder="'请输入' + baseNameMap.itemName.label"
              allow-clear
            />
          </a-form-item>
          <!-- 就职状态 -->
          <a-form-item
            :field="baseNameMap.itemStatus.key"
            :label="baseNameMap.itemStatus.label"
          >
            <a-select
              v-model="state[baseNameMap.itemStatus.key]"
              :placeholder="'请选择' + baseNameMap.itemStatus.label"
            >
              <a-option
                v-for="(item, index) of jobStatusOptions"
                :key="'jobStatus-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>
        </template>
        <template #action="{ record }">
          <a-space>
            <a-button size="small" type="text" @click="handleLook(record)">{{
              baseNameMap.btnLook.label
            }}</a-button>
          </a-space>
        </template>
      </TableLayout>
      <!-- 编辑弹窗 -->
      <EditModal
        v-bind="editHandler.props"
        @cancel="editHandler.props.visible = false"
        @save="editHandler.onSave"
      />
    </div>
    <!-- <Transition name="slide-right"> -->
    <InnerPage
      v-if="infoHandler.props[baseNameMap.itemId.key]"
      class="m-employee-info"
      @back="infoHandler.onBack"
    >
      <!-- 基本信息 -->
      <BaseInfo v-bind="infoHandler.props" @update="infoHandler.onUpdate" />
    </InnerPage>
    <!-- </Transition> -->
  </div>
</template>

<style lang="less">
  .m-employee {
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
  }
</style>
